﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MLM.Data;
using MLM.AdminCP.Class;

namespace MLM.AdminCP
{
    public static class Permission
    {
        public enum PermissionGroup
        {
            Admin = 1,
            UnderDepo = 2,
            CountryDepo = 3,
            Distributor = 4
        }
        public static long NumberCheckSum = 10101000165656;
        public static bool IsAdmin(long userId = 0)
        {
            if (userId == 0)
            {
                var savedUserId = HttpContext.Current.Session["CurrentUserId"];
                try
                {
                    if (savedUserId == null)
                    {
                        savedUserId = HttpContext.Current.Request.Cookies["CurrentUserId"].Value;
                    }
                }
                catch (Exception)
                {
                    savedUserId = 0;
                }
                userId = long.Parse(savedUserId.ToString());
            }
            bool inGroup = false;
            MLMDataContext ct = new MLMDataContext();
            try
            {
                if ((PermissionGroup)ct.Users.FirstOrDefault(it => it.UserId == userId).RoleID == PermissionGroup.Admin)
                {
                    inGroup = true;
                }
            }
            catch (Exception)
            {
                inGroup = false;
            }

            return inGroup;
        }
        public static bool IsUnderDepo(long userId = 0)
        {
            if (userId == 0)
            {
                var savedUserId = HttpContext.Current.Session["CurrentUserId"];
                try
                {
                    if (savedUserId == null)
                    {
                        savedUserId = HttpContext.Current.Request.Cookies["CurrentUserId"].Value;
                    }
                }
                catch (Exception)
                {
                    savedUserId = 0;
                }
                userId = long.Parse(savedUserId.ToString());
            }
            bool inGroup = false;
            MLMDataContext ct = new MLMDataContext();
            try
            {
                if ((PermissionGroup)ct.Users.FirstOrDefault(it => it.UserId == userId).RoleID == PermissionGroup.UnderDepo)
                {
                    inGroup = true;
                }
            }
            catch (Exception)
            {
                inGroup = false;
            }

            return inGroup;
        }
        public static bool IsCountryDepo(long userId = 0)
        {
            if (userId == 0)
            {
                var savedUserId = HttpContext.Current.Session["CurrentUserId"];
                try
                {
                    if (savedUserId == null)
                    {
                        savedUserId = HttpContext.Current.Request.Cookies["CurrentUserId"].Value;
                    }
                }
                catch (Exception)
                {
                    savedUserId = 0;
                }
                userId = long.Parse(savedUserId.ToString());
            }
            bool inGroup = false;
            MLMDataContext ct = new MLMDataContext();
            try
            {
                if ((PermissionGroup)ct.Users.FirstOrDefault(it => it.UserId == userId).RoleID == PermissionGroup.CountryDepo)
                {
                    inGroup = true;
                }
            }
            catch (Exception)
            {
                inGroup = false;
            }

            return inGroup;
        }
        public static bool IsDistributor(long userId = 0)
        {
            if (userId == 0)
            {
                var savedUserId = HttpContext.Current.Session["CurrentUserId"];
                try
                {
                    if (savedUserId == null)
                    {
                        savedUserId = HttpContext.Current.Request.Cookies["CurrentUserId"].Value;
                    }
                }
                catch (Exception)
                {
                    savedUserId = 0;
                }
                userId = long.Parse(savedUserId.ToString());
            }
            bool inGroup = false;
            MLMDataContext ct = new MLMDataContext();
            try
            {
                if ((PermissionGroup)ct.Users.FirstOrDefault(it => it.UserId == userId).RoleID == PermissionGroup.Distributor)
                {
                    inGroup = true;
                }
            }
            catch (Exception)
            {
                inGroup = false;
            }

            return inGroup;
        }
        public static int? GetGroupForUser(long userId)
        {
            MLMDataContext ct = new MLMDataContext();
            return ct.Users.FirstOrDefault(it => it.UserId == userId).RoleID;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static bool IsUserLoggedIn()
        {
            try
            {
if (HttpContext.Current.Session["CurrentUserId"] == null && HttpContext.Current.Request.Cookies["CurrentUserId"] == null)
            {
                return false;
            }
            else if (HttpContext.Current.Request.Cookies["CurrentUserId"] != null)
            {
                var data = HttpContext.Current.Request.Cookies["CurrentUserId"].Value;
                var keycookie = Util.DecryptByKey(HttpContext.Current.Request.Cookies["RandomKey"] != null ? HttpContext.Current.Request.Cookies["RandomKey"].Value : "denied", MLMEncrypt.EncryptKey);
                if (long.Parse(data) + long.Parse(keycookie) == NumberCheckSum)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else if (HttpContext.Current.Session["UserId"] != null)
            {
                return true;
            }
            else
            {
                return false;
            }
            }
            catch (Exception)
            {
                return false;
            }
            
        }
        /// <summary>
        /// check if user not login then resirect to login page
        /// </summary>
        public static void CheckLogin()
        {
            if (!IsUserLoggedIn()) { HttpContext.Current.Response.Redirect("~/AdminCP/Pages/Login.aspx?ReturnUrl=" + HttpContext.Current.Request.RawUrl); }
        }
        /// <summary>
        /// check login from login form
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="pass"></param>
        /// <returns></returns>
        public static bool CheckLoginInfo(long userId, string pass)
        {
            var isOk = false;
            MLMDataContext ct = new MLMDataContext();
            var list = ct.Users.Where(it => it.UserId == userId && it.Password == pass);
            if (list.Count() > 0)
            {
                isOk = true;
                HttpContext.Current.Session["CurrentUserId"] = HttpContext.Current.Response.Cookies["CurrentUserId"].Value = list.ToList().First().UserId.ToString();
                HttpContext.Current.Session["CurrentUserRole"] = HttpContext.Current.Response.Cookies["CurrentUserRole"].Value = list.ToList().First().RoleID.ToString();
                HttpContext.Current.Response.Cookies["CurrentUserId"].Expires = DateTime.Now.AddMonths(1);
                HttpContext.Current.Response.Cookies["CurrentUserRole"].Expires = DateTime.Now.AddMonths(1);
                HttpContext.Current.Response.Cookies["RandomKey"].Value =
                    Util.EncryptByKey((NumberCheckSum - list.ToList().First().UserId).ToString(), MLMEncrypt.EncryptKey);
                HttpContext.Current.Response.Cookies["RandomKey"].Expires = DateTime.Now.AddMonths(1);
                if (HttpContext.Current.Request.QueryString["ReturnUrl"] != null)
                {
                    HttpContext.Current.Response.Redirect(HttpContext.Current.Request.QueryString["ReturnUrl"]);
                }
                else
                {
                    HttpContext.Current.Response.Redirect("~/AdminCP/Pages/Default.aspx");
                }
            }            
            return isOk;
        }
        public static string GetCurrentUserFullName()
        {
            var fullname = "";
            try
            {
                var savedUserId = HttpContext.Current.Session["CurrentUserId"];
                try
                {
                    if (savedUserId == null)
                    {
                        savedUserId = HttpContext.Current.Request.Cookies["CurrentUserId"].Value;
                    }
                }
                catch (Exception)
                {
                    savedUserId = 0;
                }
                var userid = long.Parse(savedUserId.ToString());
                MLMDataContext ct = new MLMDataContext();
                User firstOrDefault = ct.Users.FirstOrDefault(it => it.UserId == userid);
                fullname = firstOrDefault.FirstName + " " + firstOrDefault.LastName;
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write(ex.Message);
            }
            return fullname;
        }
        public static void DoLogout()
        {
            HttpContext.Current.Session["CurrentUserId"] = null;
            HttpContext.Current.Session["CurrentUserRole"] = null;            
            HttpContext.Current.Response.Cookies["CurrentUserId"].Value = null;
            HttpContext.Current.Response.Cookies["RandomKey"].Value = null;
            HttpContext.Current.Response.Cookies["CurrentUserId"].Expires = DateTime.Now.AddDays(-1);
            HttpContext.Current.Response.Cookies["CurrentUserRole"].Expires = DateTime.Now.AddDays(-1);
            HttpContext.Current.Response.Cookies["RandomKey"].Expires = DateTime.Now.AddDays(-1);
            HttpContext.Current.Response.Redirect("~/AdminCP/Pages/Login.aspx");
        }
        public static void CheckIsAdmin()
        {
            Permission.CheckLogin();
            if (!Permission.IsAdmin())
            {
                HttpContext.Current.Response.Redirect("~/AdminCP/Pages/AccessDenied.aspx");
                HttpContext.Current.Response.End();
            }
        }
        public static void CheckIsUnderDepo()
        {
            Permission.CheckLogin();
            if (!Permission.IsUnderDepo())
            {
                HttpContext.Current.Response.Redirect("~/AdminCP/Pages/AccessDenied.aspx");
                HttpContext.Current.Response.End();
            }
        }
        public static long GetCurrentRole()
        {
            try
            {
                var savedRole = HttpContext.Current.Session["CurrentUserRole"];
                try
                {
                    if (savedRole == null)
                    {
                        savedRole = HttpContext.Current.Request.Cookies["CurrentUserRole"].Value;
                    }
                }
                catch (Exception)
                {
                    savedRole = 0;
                }
                return long.Parse(savedRole.ToString());
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Redirect("~/AdminCP/Pages/Login.aspx?ReturnUrl=" + HttpContext.Current.Request.RawUrl);
                return 0;
            }
        }
        public static long GetCurrentUserId()
        {
            try
            {
                var savedUserId = HttpContext.Current.Session["CurrentUserId"];
                try
                {
                    if (savedUserId == null)
                    {
                        savedUserId = HttpContext.Current.Request.Cookies["CurrentUserId"].Value;
                    }
                }
                catch (Exception)
                {
                    savedUserId = 0;
                }
                return long.Parse(savedUserId.ToString());
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Redirect("~/AdminCP/Pages/Login.aspx?ReturnUrl=" + HttpContext.Current.Request.RawUrl);
                return 0;
            }
        }

        public static int? GetUserRole(MLMDataContext ct, object UserId)
        {
            //dang code
            long _UserId = long.Parse(UserId.ToString());
            return ct.Users.FirstOrDefault(it => it.UserId == _UserId).RoleID;
        }
        public static string RandomPassword(int min = 10000, int max = 2000000000)
        {
            Random random = new Random();
            return random.Next(min, max).ToString();
        }
    }
}